<template>
  <div>
    <el-header>
      <van-nav-bar title="咖啡师-考评端" right-text="退出登录" left-arrow @click-left="goBack" @click-right="logout"/>

    </el-header>
    <el-container style="height: max-content;">
      <el-aside width="15%" style="height: 100%;background-color: white">
        <div style="font-weight: bold; font-size: large">
          {{ '学生编号：' + stu }}<br>
          {{ '考位编号：' + stationName }}<br>
          {{ '考位顺序：' + order }}<br>
        </div>
        <br>
        <el-button @click="absent" type="warning">学生缺考</el-button>
        <br><br>
        <!-- <el-button @click="openCritical" type="danger">严重错误</el-button> -->
       <el-button @click="refresh" type="primary">刷新数据</el-button>
<!--        <br><br>-->
        <el-button class="back-to-top" @click="scrollToTop"
                   v-show="showButton" type="info"
                   circle
                   icon="el-icon-top"
                   size="large" />
        <el-button class="refresh-btn" @click="refresh"
                   type="primary"
                   circle
                   icon="el-icon-refresh"
                   size="large" />
      </el-aside>
      <el-dialog
        title="是否有严重错误"
        :visible.sync="isCritical"
        width="30%"
        center
        :append-to-body='true'
      >
        <span>如在操作过程中出现违反食品安全或设备使用安全等规定的严重错误，则取消考生本题成绩。</span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="isCritical = false">取 消</el-button>
          <el-button type="danger" @click="criticalERROR"
            >确 定</el-button
          >
        </span>
      </el-dialog>

      <el-container>
        <el-main>
<!--          <van-pull-refresh v-model="refreshing" @refresh="onRefresh" style="width: 95%;">-->
            <van-list v-model="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">

              <el-card v-for="bigQuestions in list" :key="bigQuestions.id" :title="bigQuestions" class="bigQues-card"
                       shadow="never"
              >
                <div slot="header" class="clearfix">
                  <span style="font-weight: bold;">{{ bigQuestions.OriginalSn + '. '}}</span>
                  <span style="font-weight: bold; font-size: x-large">{{ bigQuestions.title }}</span>
                </div>
                <div style="margin-bottom: 3%;white-space: pre-line;">
                  {{ bigQuestions.content }}
                </div>

                <el-collapse accordion>
                  <el-collapse-item>
                    <template slot="title">
                      <span style="font-weight: bold">{{ '展开小题' }}</span>
                    </template>

                    <el-card v-if="item.type !== '拍照题'"
                             v-for="item in bigQuestions.QA" :key="item.id" :title="item" name="stepper"
                             :label="item.question" label-width="70%"
                    >
                      <!-- 小题标题 -->
                      <div slot="header" class="clearfix">

                        <div v-if="item.type === '多填空题' "
                             v-for="qes in item.answer" :key="qes.id"
                             label-width="70%"
                             style="font-weight: bold; font-size: large"
                        >
                          {{ snFormatter(bigQuestions.id, item.questionId)+'. '+'题目：' + qes.q }}
                          <br>
                          <span style="color: #3A71A8">{{'学生答案：' + qes.a }}</span>
                        </div>
                        <div v-if="item.type === '填空题'"
                             label-width="70%"
                             style="font-weight: bold; font-size: large"
                        >
                          {{ snFormatter(bigQuestions.id, item.questionId)+'. '+item.question }}
                        </div>
                        <div v-if="item.type === '操作题'"
                             label-width="70%"
                             style="font-weight: bold; font-size: large"
                        >
                          {{ snFormatter(bigQuestions.id, item.questionId)+'. '+item.question }}
                        </div>
                        <div v-if="item.type === '单选题'"
                             label-width="70%"
                             style="font-weight: bold; font-size: large"
                        >
                          <span> {{ snFormatter(bigQuestions.id, item.questionId)+'. '+item.question[0].title }} </span>
                        </div>
                        <div v-if="item.type === '判断题'"
                             label-width="70%"
                             style="font-weight: bold; font-size: large"
                        >
                          <span style="color: red"> 是否有严重错误 </span>
                        </div>
                        <div v-if="item.type === '拍照题'"
                             label-width="70%"
                             style="font-weight: bold; font-size: large"
                        >
                          <span> 拍照留档 </span>
                        </div>

                      </div>
                      <!--############-->
                      <!-- 内容显示区 -->
                      <div>
                        <div v-if="item.type === '单选题'">
                          <span style="font-weight: bold; font-size: large">选项：</span>
                          <span v-for="opt in item.question[0].options" :key="opt.id"
                                style="font-weight: bold; font-size: large">
                            {{ opt[Object.keys(opt)[0]] }}
                          </span>
                          <br>
                          <span v-if="item.answer === null"
                                style="font-weight: bold; font-size: medium; color: #3A71A8">
                            学生答案：学生尚未答题
                          </span>
                          <span v-else
                                style="font-weight: bold; font-size: medium; color: #3A71A8">
                            {{ '学生答案：' + item.answer }}
                          </span>

                        </div>
                        <div v-if="item.type === '填空题'">
                          <span v-if="item.answer === null"
                                style="font-weight: bold; font-size: medium; color: #3A71A8">
                            学生答案：学生尚未答题
                          </span>
                          <span v-else
                                style="font-weight: bold; font-size: medium; color: #3A71A8">
                            {{ '学生答案：' + item.answer }}
                          </span>

                        </div>
                        <div>{{ '评分标准：' + item.standard }}</div>
                        <div v-if="item.type !== '判断题' && item.type !== '拍照题' ">{{ '题目类型：' + item.type }}</div>
                        <div v-if="item.type !== '判断题' && item.type !== '拍照题' ">{{ '当前分数：' + item.score + '/' + item.totalScore }}</div>
                      </div>
                      <!-- 右下角功能按钮（评分按钮）区域 -->
                      <div style="float: right; margin: 10px;">
                        <van-stepper
                          v-if="item.score === '-1.0' "
                          :step="item.totalScore"
                          :min="0"
                          :max="item.totalScore"
                          disabled
                        />
                        <van-stepper
                          v-else-if="item.type !== '判断题' && 
                                item.type !== '拍照题' && 
                                item.scoreType === 4 && 
                                item.score !== '-1.0' "
                          v-model="item.score"
                          :step="item.scoreStep"
                          :min="0"
                          :max="item.totalScore"
                          @change="onChangeScore($event, item.id)"
                          disable-input
                        />
                        <van-stepper
                          v-else-if="item.type !== '判断题' && 
                                    item.type !== '拍照题' && 
                                    item.scoreType === 3 && 
                                    item.score !== '-1.0' "
                          v-model="item.score"
                          :step="item.totalScore"
                          :min="0"
                          :max="item.totalScore"
                          @change="onChangeScore($event, item.id)"
                          disable-input
                        />
                        
                        <el-button v-else-if="item.type === '拍照题'" @click="takePhoto(bigQuestions)">拍照留档</el-button>
                        <el-button v-else @click="criticalERROR(bigQuestions)" type="danger">是否有严重错误</el-button>
                      </div>
                    </el-card>
                  </el-collapse-item>
                </el-collapse>

              </el-card>
            </van-list>
<!--          </van-pull-refresh>-->

        </el-main>
      </el-container>

    </el-container>
    <center>
      <el-button @click="finish" type="primary" style="width: 70%">结束评分</el-button>
    </center>
    <el-footer>
      {{ "" }}
    </el-footer>


  </div>
</template>

<script>
import { listPaper, updateScore, reportCriticalError, reportAbsent, finishExam} from '@/api/examiner/examiner.js'

export default {
  name: 'Examiner',
  data() {
    return {
      isCritical: false,
      examId: null,
      paperId: null,
      stu: null,
      stationName: null,
      order: null,
      tid: null,
      list: [],
      loading: false,
      finished: false,
      refreshing: false,
      showButton:true
    }
  },
  watch: {},
  created() {
    // this.getInfoList()
    this.examId = this.$route.query.examId

    this.paperId = this.$route.query.paperId
    this.stu = this.$route.query.stu
    this.order = this.$route.query.order
    this.tid = this.$route.query.tid
    this.stationName = this.$route.query.stationName
  },
  mounted() {
    window.addEventListener('scroll', this.handleScroll);
  },
  beforeDestroy() {
    window.removeEventListener('scroll', this.handleScroll);
  },
  methods: {

    getInfoList() {
      this.loading = true
      this.paperId = this.$route.query.paperId

      listPaper(this.paperId).then(response => {
          // console.log('*********', response)
          const _t_List = response.data[0]
          for (const bigQues in _t_List) {
            for (const ques in _t_List[bigQues].QA) {
              if (_t_List[bigQues].QA[ques].question != null) {
                _t_List[bigQues].QA[ques].question = _t_List[bigQues].QA[ques].question.replace(/\n/g, '')
                _t_List[bigQues].QA[ques].question = _t_List[bigQues].QA[ques].question.replace(/\r/g, '')
                _t_List[bigQues].QA[ques].question = _t_List[bigQues].QA[ques].question.replace(/\t/g, '')

                if (_t_List[bigQues].QA[ques].type == '多填空题' || _t_List[bigQues].QA[ques].type == '单选题') {
                  _t_List[bigQues].QA[ques].question = eval(_t_List[bigQues].QA[ques].question)
                }
              }
              if (_t_List[bigQues].QA[ques].answer != null) {
                _t_List[bigQues].QA[ques].answer = _t_List[bigQues].QA[ques].answer.replace(/\n/g, '')
                _t_List[bigQues].QA[ques].answer = _t_List[bigQues].QA[ques].answer.replace(/\r/g, '')
                _t_List[bigQues].QA[ques].answer = _t_List[bigQues].QA[ques].answer.replace(/\t/g, '')
                if (_t_List[bigQues].QA[ques].type == '多填空题') {
                  _t_List[bigQues].QA[ques].answer = eval(_t_List[bigQues].QA[ques].answer)
                }
              }
            }
          }
          this.list = _t_List
        console.log('LIST:', this.list)

          this.total = response.total
          this.loading = false
        }
      ).catch(res => {
        console.log('****ERROR*****', res)
      })
    },

    onLoad() {
      setTimeout(() => {
        if (this.refreshing) {
          this.list = []
          this.refreshing = false
        }
        this.getInfoList()
        this.loading = false
        this.finished = true

        if (this.list.length >= 40) {
          this.finished = true
        }
      }, 1000)
    },
    onRefresh() {
      // 清空列表数据
      this.finished = false
      // 重新加载数据
      // 将 loading 设置为 true，表示处于加载状态
      this.loading = true
      this.onLoad()
    },
    onChangeScore(score, qid) {
      // console.log("score value:",value,"AAA;",e)

      updateScore(qid, score).then(res => {
        // console.log('******RES*******', res)
      }).catch(res => {
        console.log('****ERROR*****', res)
      })
    },
    openCritical(item){
      // console.log("e:",e)
      
      this.isCritical = true
    },
    takePhoto(bigQuestions){

    },
    criticalERROR(bigQuestions){
      this.$confirm('此操作将会取消该大题成绩, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(() => {
        reportCriticalError(this.paperId, bigQuestions.id).then(res => {
          // console.log('******reportCriticalError*******', res)
          this.$message({
            type: 'error',
            message: '严重错误，本大题成绩取消!'
          });
          this.getInfoList()
          // this.$router.back()
        })

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    },
    absent(){
      this.$confirm('此操作会判定考生缺考并取消考试, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(() => {
        reportAbsent(this.paperId).then(res => {
          // console.log('******Absent*******', res)
          this.$message({
            type: 'error',
            message: '考生缺考，考试结束!'
          });
          this.$router.back()
        })

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    },
    refresh(){
      this.getInfoList()
    },
    finish(){
      this.$confirm('确定完成评分并结束考试, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log('TID:',this.tid,'examId:',this.examId)
        finishExam(this.tid,this.examId).then(res => {
          console.log('******Finish*******', res)
          this.$message({
            type: 'success',
            message: '考试结束!'
          });
          this.$router.back()
        })

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    },
    goBack() {
      this.$router.back()
    },
    async logout() {
      this.$confirm('确定注销并退出系统吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$store.dispatch('LogOut').then(() => {
          location.href = '/index'
        })
      }).catch(() => {
      })
    },

    orderList(attr) {
      return function(a, b) {
        return a[attr] - b[attr]
      }
    },
    isObject(item) {
      return typeof item === 'object' && item !== null && !Array.isArray(item)
    },
    isArray(item) {
      return Array.isArray(item)
    },
    handleScroll() {
      // 当页面滚动超过一定距离时，显示回到顶部按钮
      const scrollPosition = window.pageYOffset || document.documentElement.scrollTop;
      this.showButton = scrollPosition > 100;
    },
    scrollToTop() {
      // 平滑滚动到页面顶部
      const scrollDuration = 500; // 滚动持续时间（毫秒）
      const scrollStep = -window.scrollY / (scrollDuration / 15);

      const scrollInterval = setInterval(() => {
        if (window.scrollY !== 0) {
          window.scrollBy(0, scrollStep);
        } else {
          clearInterval(scrollInterval);
        }
      }, 15);
    },
    snFormatter(OriginalSn,questionId){
      let snNumStr = ""+OriginalSn
      let qsnNumStr = ""+questionId
      qsnNumStr = qsnNumStr.replace(snNumStr,'')
      // console.log("Original:",snNumStr,"ques:",qsnNumStr)
      return qsnNumStr
    }


  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
.container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}

.bigQues-card {
  margin: 3%;
  //background-color: #8492a6;
}
.back-to-top {
  position: fixed;
  bottom: 20px;
  /* 样式可根据需求自定义 */
}
.refresh-btn {
  position: fixed;
  bottom: 90px;
  /* 样式可根据需求自定义 */
}
.critical-btn {
  position: fixed;
  bottom: 160px;
  /* 样式可根据需求自定义 */
}
.footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}
</style>
